<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/7/3
 * Time: 11:39
 */

namespace app\service;


use Redis\Redis;
use think\Db;

class MemberService
{
    /**
     * @param $code
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 更新redis
     */
    function changeRedis($code)
    {
        $redis = new Redis();
        $info = Db::table('member m')
            ->field('m.*,mp.*,mc.*,ml.title,(select  COALESCE(sum(earnings_price),0) from member_business mb where mb.member_code = m.code and mb.status != -1 and place_status=1) combat_power')
            ->leftJoin('member_property mp', 'mp.member_code=m.code and mp.is_fake=1')
            ->leftJoin('member_collection mc', 'mc.member_code=m.code')
            ->leftJoin('member_level ml', 'ml.level=m.level')
            ->where(array('code' => $code))->find();
        # 头像地址
        $info['head_portrait'] = imgurl($info['head_portrait']);
        # 微信收款码
        $info['wx_img'] = imgurl($info['wx_img']);
        # 支付宝收款码
        $info['ali_img'] = imgurl($info['ali_img']);
        # 银联收款码
        $info['union_img'] = imgurl($info['union_img']);
        $info['gold'] = priceFormat($info['gold']);
        $info['materials'] = priceFormat($info['materials']);
        $info['integral'] = priceFormat($info['integral']);
        $info['combat_power'] = priceFormat($info['combat_power']);
        $redis->hSetJson('memberInfo', $code, $info);
    }

    /**
     * @param $memberCode 推荐人
     * @param $pCode 推荐的玩家
     * @param string $mark 标识  activation=>激活  level=>升级
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 推荐人加收益
     */
    function recommendedRevenue($memberCode, $pCode, $mark = 'level')
    {
        $memberCode = strtoupper($memberCode);
        $_redis = new Redis();
        # 查询直推的当前人数
        $recommendNum = $_redis->hGetJson('recommendNum', $memberCode);
        if (empty($recommendNum)) {
            $recommendNum = Db::table('member')->where(array('p_code' => $memberCode, 'status' => 5))->count();
        } else {
            $recommendNum += 1;
        }
        $_redis->hSetJson('recommendNum', $memberCode, $recommendNum);
        # 判断是第几个人(第一个38,第二个58,第三个及以后78,每推荐10个额外108)
        if ($mark == 'activation') {
            # 激活
            $goldNum = 28;
            # 推荐玩家奖励
            $typeBranch = 9;
        } else {
            # 达到级别
            if ($recommendNum == 1) {
                $goldNum = 20;
            } elseif ($recommendNum == 2) {
                $goldNum = 30;
            } else {
                $goldNum = 40;
            }
            # 推荐达成奖励
            $typeBranch = 10;
        }
        # 添加金币
        MemberService::recommendBranch($memberCode, $goldNum, 5, 1, $pCode, 1, $typeBranch);
        # 查询上一级(加18)
        $p_code = Db::table('member')->field('p_code')->where(array('code' => $memberCode))->find()['p_code'];
        if (!empty($p_code)) {
            if ($mark == 'activation') {
                # 激活
                $gold_num = 18;
                # 新增关联玩家
                $type_ranch = 11;
            } else {
                # 达到级别(三级)
                $gold_num = 10;
                # 关联玩家达成
                $type_ranch = 12;
            }
            MemberService::recommendBranch($p_code, $gold_num, 6, 2, $memberCode, 2, $type_ranch);
            /*# 再查上一级(加18)
            $pp_code = Db::table('member')->field('p_code')->where(array('code' => $p_code))->find()['p_code'];
            if (!empty($pp_code)) {
                MemberService::recommendBranch($pp_code, 18, 6, 2, $memberCode);
            }*/
        }
    }

    /**
     * @param $memberCode 推荐人
     * @param $goldNum 得到的金币数量
     * @param $goldType 金币类型
     * @param $incomeType 收益类型
     * @param $pCode 推荐的玩家
     * @param int $type_branch 类型分支
     * @param int $integralLevel 积分级别
     * @throws \think\Exception
     */
    function recommendBranch($memberCode, $goldNum, $goldType, $incomeType, $pCode, $integralLevel = 0, $type_branch = 0)
    {
        $_redis = new Redis();
        # 添加金币
        Db::table('member_property')->where(array('member_code' => $memberCode))->setInc('gold', $goldNum);
        Db::table('member_property')->where(array('member_code' => $memberCode))->setInc('income', $goldNum);
        # 金币记录
        MemberService::addLog_gold($memberCode, $goldNum, $goldType, strtoupper($pCode), $type_branch);
        # 添加收益记录
        MemberService::addLog_income($memberCode, $goldNum, $incomeType);
        $integral = 0;
        if ($integralLevel == 1) {
            # 推荐新玩家加98积分
            $integral = 98;
            # 添加积分
            Db::table('member_property')->where(array('member_code' => $memberCode))->setInc('integral', $integral);
            # 积分记录$code, $integral, $status, $type, $memberp_code = '', $type_branch = 0
            MemberService::addLog_integral($memberCode, $integral, 1, 13, strtoupper($pCode));
        } elseif ($integralLevel == 2) {
            # 上一家28积分
            $integral = 28;
            # 添加积分
            Db::table('member_property')->where(array('member_code' => $memberCode))->setInc('integral', $integral);
            # 积分记录
            MemberService::addLog_integral($memberCode, $integral, 1, 14, strtoupper($pCode));
        }
        # 更新redis
        $memberInfo = $_redis->hGetJson('memberInfo', $memberCode);
        if (!empty($memberInfo)) {
            $memberInfo['gold'] = priceFormat($memberInfo['gold'] + $goldNum);
            $memberInfo['income'] = priceFormat($memberInfo['income'] + $goldNum);
            $memberInfo['integral'] = priceFormat($memberInfo['integral'] + $integral);
            $_redis->hSetJson('memberInfo', $memberCode, $memberInfo);
        }
    }

    /**
     * @param string $memberCode 要查询的玩家ID
     * @param int $memberTeamId 团队ID
     * @param int $people 关系  1=>团队玩家  2=>我的直推  3=>我的隔代  4=>其他玩家
     * @return array
     * * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 查询对应关系的玩家ID
     */
    function relationship($memberCode, $memberTeamId, $people)
    {
        if (!empty($memberCode) and !empty($memberTeamId) and !empty($people)) {
            ## 查询玩家对应关系的ID
            if ($people == 1) {
                # 团队玩家(B,C,D)
                $peopleInfo = Db::table('member')->field('code')
                    ->where("code != '" . $memberCode . "'")
                    ->where("(code in ((select code from member where p_code in 
            (select code from member where p_code in(select code from member where p_code = '" . $memberCode . "'))),
            (select code from member where p_code in(select code from member where p_code = '" . $memberCode . "')),
            (select code from member where p_code = '" . $memberCode . "')))")
                    ->select();
            } elseif ($people == 2) {
                # 我的直推(B)
                $peopleInfo = Db::table('member')->field('code')->where("code != '" . $memberCode . "'")->where(array('p_code' => $memberCode))->select();
            } elseif ($people == 3) {
                # 我的隔代(C)
                $peopleInfo = Db::table('member')
                    ->field('code')
                    ->where("code in (select code from member where p_code in (select code from member where p_code = '" . $memberCode . "'))")
                    ->where("code != '" . $memberCode . "'")
                    ->select();
            } else {
                # 其他玩家(D)
                $peopleInfo = Db::table('member')
                    ->field('code')
                    ->where("code != '" . $memberCode . "'")
                    ->where("(code in (select code from member where p_code in 
                    (select code from member where p_code in(select code from member where p_code = '" . $memberCode . "'))))")
                    ->select();
            }
            $peopleInfo = array_column($peopleInfo, 'code');
            $peopleCount = count($peopleInfo);
            if ($peopleCount > 0) {
                return array('status' => true, 'msg' => '查询成功', 'peopleInfo' => $peopleInfo, 'peopleCount' => $peopleCount);
            } else {
                return array('status' => false, 'msg' => '玩家信息列表为空');
            }
        } else {
            return array('status' => false, 'msg' => '参数存在空值');
        }
    }

    /**
     * @param $memberCode
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @content 领取体验行业
     */
    function receiveBusiness($memberCode)
    {
        if (!empty($memberCode)) {
            $redis = new Redis();
            # 判断状态
            $memberInfo = $redis->hGetJson('memberInfo', $memberCode);
            if ($memberInfo['status'] == 5) {
                return array('status' => false, 'msg' => '已经激活,无需激活');
            } else {
                # 查询是否满足激活条件
//                $logIntegral = Db::table('log_integral')->where(array('member_code' => $memberCode, 'type_branch' => 7))->sum('total_money');
//                if ($logIntegral >= 388) {
                # 满足条件,添加体验行业,加50金币 , 加388积分 , 50元卡券一张 15天有效期
                /*# 查询体验行业
                $industryInfo = Db::table('industry i')
                    ->field('i.id,i.title,i.logo,i.level,day_income,min_num,cycle_period')
                    ->leftJoin('industry_cycleincome ic', 'ic.industry_id=i.id')
                    ->where("is_del=2 and category=2 and status=1")
                    ->order("ic.min_num asc")
                    ->find();
                if (!empty($industryInfo)) {
                    $teamId = $memberInfo['team_id'];
                    # 查询团队
                    $team = Db::table('team')
                        ->field('matching_type,team_set')
                        ->where(array('id' => $teamId, 'is_fake' => 1))
                        ->find();
                    if (!empty($team)) {
                        if ($team['matching_type'] == 2) {
                            $teamId .= $team['team_set'];
                        }
                    }
                    $businessInfo = array(
                        'member_code' => $memberCode,
                        'industry_id' => $industryInfo['id'],
                        'industry_imgurl' => $industryInfo['logo'],
                        'industry_title' => $industryInfo['title'],
                        'day_income' => $industryInfo['min_num'] * $industryInfo['day_income'],
                        'status' => 1,
                        'buy_time' => date("Y-m-d H:i:s"),
                        'sell_time' => date('Y-m-d H:i:s', strtotime('+ ' . $industryInfo['cycle_period'] . ' days')),
                        'growth_cycle' => $industryInfo['cycle_period'],
                        'earnings_ratio' => $industryInfo['day_income'],
                        'earnings_price' => $industryInfo['min_num'] * $industryInfo['day_income'] * $industryInfo['cycle_period'],
                        'earnings_level' => $industryInfo['level'],
                        'buy_price' => $industryInfo['min_num'],
                        'team_id' => $teamId,
                        'sale_price' => $industryInfo['min_num'] + ($industryInfo['min_num'] * $industryInfo['day_income'] * $industryInfo['cycle_period'])
                    );
                    # 添加玩家生意信息
                    $businessId = Db::table('member_business')->insert($businessInfo);
                    # 开两个格子
                    Db::table('member_business_grid')->where("grid in (1,2)")->where(array('member_code' => $memberCode))->update(array('status' => 1));
                    # 放到第一个格子里
                    Db::table('member_business_grid')
                        ->where(array('grid' => 1, 'member_code' => $memberCode))
                        ->update(array(
                            'member_business_id' => $businessId
                        ));
                } else {
                    return array('status' => false, 'msg' => '体验行业信息为空');
                }*/
                /*
                 * 'combat_power' => $industryInfo['min_num'],
                 * $memberInfo['combat_power'] = $industryInfo['min_num'];
                 * */
                # 修改用户状态 , 战力值
                Db::table('member')->where(array('code' => $memberCode))->update(array('status' => 5, 'is_show' => 1, 'activation_time' => date("Y-m-d H:i:s")));
                # 加230金币
                Db::table('member_property')->where(array('member_code' => $memberCode))->setInc('bind_gold', 230);
                Db::table('member_property')->where(array('member_code' => $memberCode))->setInc('income', 230);
                # 加188积分
                Db::table('member_property')->where(array('member_code' => $memberCode))->setInc('integral', 188);
                # 金币记录
                MemberService::addLog_gold($memberCode, 230, 3, '', 7);
                # 积分记录
                MemberService::addLog_integral($memberCode, 188, 1, 3);
                # 收益记录
                MemberService::addLog_income($memberCode, 230, 5, 7);
                # 赠送5元卡券 15天
                $voucherInfo = Db::table('voucher')->where(array('id' => 2))->find();
                Db::table('member_voucher')->insert(array(
                    'member_code' => $memberCode,
                    'voucher_title' => $voucherInfo['title'],
                    'voucher_id' => 2,
                    'price' => $voucherInfo['price'],
                    'expiration_time' => date('Y-m-d H:i:s', strtotime('+ 15 days')),
                    'get_time' => date("Y-m-d H:i:s"),
                    'use_status' => 1,
                    'source' => 3,
                    'voucher_perioy' => 15
                ));
                # 开两个格子
                Db::table('member_business_grid')->where(array('member_code' => $memberCode))->where("grid in (1,2)")->update(array('status' => 1));
                $redis->hDel('member_business', $memberCode);
                # 更新redis
                $memberInfo['gold'] = priceFormat($memberInfo['gold'] + 230);
                $memberInfo['integral'] = priceFormat($memberInfo['integral'] + 188);
                $memberInfo['income'] = priceFormat($memberInfo['income'] + 230);
                $memberInfo['status'] = 5;
                $memberInfo['is_show'] = 1;
                $memberInfo['activation_time'] = date("Y-m-d H:i:s");
                $redis->hSetJson('memberInfo', $memberCode, $memberInfo);
                return array('status' => true, 'msg' => '激活成功');
//                } else {
//                    # 不满足激活条件
//                    return array('status' => false, 'msg' => '不满足激活条件');
//                }
            }
        } else {
            return array('status' => false, 'msg' => '参数为空');
        }
    }

    /**
     * @param int $activeId 活动id
     * @param int $category 活动类型  1 大转轮 2 任务  3答题  4 签到
     * @param $memberInfo  用户信息
     * @param bool $quantityJudge 是否需要上架数量判断
     * @param bool $singleJudge 是否需要判断单人中奖次数
     * @param bool $rewardRate 是否需要判断奖品概率
     * @param string $p_code 推荐人ID
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 活动领取奖励
     */
    function giveReward($memberInfo, $activeId = 0, $category = 3, $quantityJudge = true, $singleJudge = true, $rewardRate = true, $p_code = '')
    {
        if (!empty($memberInfo)) {
            # 查询奖励列表
            $rewardList = Db::table('active_reward')
                ->field('active_reward.id,category,title,reward_num,stock_num,unit,reward_rate,
                (case category 
            when 1 then\'积分\'
            when 2 then \'金币\'
            when 3 then \'卡券\'
            when 4 then \'恢复券\'
            end) cate,
                reward_times,validity_period,voucher_id,worth,
                (select count(id) from active_rewardlog where reward_id=active_reward.id and member_code = "' . $memberInfo['code'] . '") winningTimes')
                ->where(array('active_id' => $activeId, 'active_category' => $category))
                ->select();
            if (!empty($rewardList)) {
                if ($category == 1) {
                    # 大转轮,判断概率是否为1
                    $probability = array_sum(array_column($rewardList, 'reward_rate'));
                    if ($probability < 1) {
                        # 奖品总概率小于1 ,用谢谢参与补齐
                        array_push($rewardList, array('title' => '谢谢参与', 'reward_rate' => priceFormat(1 - $probability)));
                    }
                }
                # 奖品概率
                $_arr = array();
                /*# 是否需要上架数量判断
                $quantityJudge = true;
                # 是否需要判断单人中奖次数
                $singleJudge = true;
                # 是否需要判断奖品概率
                $rewardRate = true;*/
                foreach ($rewardList as $k => $v) {
                    $mark = true;
                    if ($v['title'] != '谢谢参与') {
                        if ($quantityJudge) {
                            # 需要判断上架数量
                            if ($v['stock_num'] <= 0) {
                                $mark = false;
                                unset($rewardList[$k]);
                            }
                        }
                        if ($singleJudge) {
                            # 需要判断单人中奖次数
                            if ($v['winningTimes'] >= $v['reward_times']) {
                                $mark = false;
                                unset($rewardList[$k]);
                            }
                        }
                    }
                    if ($mark) {
                        # 奖品概率数组赋值
                        $_arr[$k] = $v['reward_rate'];
                    }
                }
                if ($rewardRate) {
                    # 需要判断奖品概率
                    $rid = MemberService::get_rand($_arr);
                    if ($rid == -1) {
//                        return array('status' => true, 'msg' => '未中奖', 'rewardList' => $rewardList, 'key' => key($rewardList), 'integral_num' => 0);
                        return array('status' => false, 'msg' => '未中奖');
                    }
                    $rewardListArr = $rewardList;
                    $rewardList = array();
                    $rewardList[$rid] = $rewardListArr[$rid];
                    if ($rewardList[$rid]['title'] == '谢谢参与') {
                        return array('status' => false, 'msg' => '未中奖');
                    }
//                    dump($rewardList[$rid]);die;
                }
                $integral_num = 0;
                if (!empty($rewardList)) {
                    # 活动奖励类型
                    $type_branch = getTypeBranch($category);
                    #redis
                    $redis = new Redis();
                    # 首页奖励轮播
                    $scrollArr = array();
                    # 兑换奖品
                    foreach ($rewardList as $k => $v) {
                        if ($v['title'] != '谢谢参与') {
                            # 定义卡券信息
                            $voucherInfo = array('title' => '', 'price' => 0);
                            if ($v['category'] == 1) {
                                $integral_num += $v['reward_num'];
                                # 积分
                                $res = Db::table('member_property')->where(array('member_code' => $memberInfo['code']))->setInc('integral', $v['reward_num']);
                                if ($res) {
                                    # 积分记录
                                    MemberService::addLog_integral($memberInfo['code'], $v['reward_num'], 1, 4, '', $type_branch);
                                    # 修改redis信息
                                    $memberInfo['integral'] = priceFormat($memberInfo['integral'] + $v['reward_num']);
                                }
                            } elseif ($v['category'] == 2) {
                                # 金币
                                $res = Db::table('member_property')->where(array('member_code' => $memberInfo['code']))->setInc('gold', $v['reward_num']);
                                Db::table('member_property')->where(array('member_code' => $memberInfo['code']))->setInc('income', $v['reward_num']);
                                if ($res) {
                                    # 金币记录
                                    MemberService::addLog_gold($memberInfo['code'], $v['reward_num'], 4, '', $type_branch);
                                    # 收益记录
                                    MemberService::addLog_income($memberInfo['code'], $v['reward_num'], 5, $category);
                                    # 修改redis信息
                                    $memberInfo['gold'] = priceFormat($memberInfo['gold'] + $v['reward_num']);
                                    $memberInfo['income'] = priceFormat($memberInfo['income'] + $v['reward_num']);
                                }
                            } elseif ($v['category'] == 3) {
                                # 卡券
                                # 查询卡券价值和名称
                                $voucherInfo = Db::table('voucher')->field('title,price')->where(array('id' => $v['voucher_id']))->find();
                                $voucherArr = array();
                                for ($i = 0; $i < $v['reward_num']; $i++) {
                                    array_push($voucherArr, array(
                                        'member_code' => $memberInfo['code'],
                                        'voucher_title' => $voucherInfo['title'],
                                        'voucher_id' => $v['voucher_id'],
                                        'price' => $voucherInfo['price'],
                                        'expiration_time' => date('Y-m-d H:i:s', strtotime('+ ' . $v['validity_period'] . ' days')),
                                        'get_time' => date("Y-m-d H:i:s"),
                                        'source' => 1,
                                        'source_branch' => $type_branch,
                                        'voucher_perioy' => $v['validity_period']
                                    ));
                                }
                                $res = Db::table('member_voucher')->insertAll($voucherArr);
                            } elseif ($v['category'] == 4) {
                                # 恢复材料
                                $res = Db::table('member_property')->where(array('member_code' => $memberInfo['code']))->setInc('materials', $v['reward_num']);
                                if ($res) {
                                    # 恢复材料记录
                                    MemberService::addLog_materials($memberInfo['code'], $v['reward_num'], 3, 1, $type_branch);
                                    # 修改redis信息
                                    $memberInfo['materials'] = priceFormat($memberInfo['materials'] + $v['reward_num']);
                                }
                            }
                            # 奖励领取记录
                            Db::table('active_rewardlog')->insert(array(
                                'active_id' => $activeId,
                                'member_code' => $memberInfo['code'],
                                'nickname' => $memberInfo['name'],
                                'thumb' => $memberInfo['head_portrait'],
                                'create_time' => date("Y-m-d H:i:s"),
                                'reward_id' => $v['id'],
                                'reward_title' => $v['title'],
                                'reward_num' => $v['reward_num'],
                                'unit' => $v['unit'],
                                'validity_period' => $v['validity_period'],
                                'voucher_id' => $v['voucher_id'],
                                'voucher_title' => $voucherInfo['title'],
                                'voucher_price' => $voucherInfo['price'],
                                'active_category' => $category,
                                'reward_cate' => $v['category']
                            ));
                            if ($category == 1) {
                                # 大转轮,添加活动参加记录
                                Db::table('active_joinlog')->insert(array(
                                    'active_id' => $activeId,
                                    'member_code' => $memberInfo['code'],
                                    'nickname' => $memberInfo['name'],
                                    'thumb' => $memberInfo['head_portrait'],
                                    'create_time' => date("Y-m-d H:i:s"),
                                    'join_status' => 1,
                                    'join_time' => date("Y-m-d H:i:s"),
                                    'recommend_code' => $p_code
                                ));
                            }
                            array_push($scrollArr, '恭喜“' . $memberInfo['name'] . '”获得' . $v['title'] . $v['reward_num'] . $v['unit']);
                            # 更新redis
                            $redis->hSetJson('memberInfo', $memberInfo['code'], $memberInfo);
                            if (!empty($scrollArr)) {
                                # 添加轮播消息
                                ScrollborderService::scroll_add($scrollArr);
                            }
                        }
                    }
                    return array('status' => true, 'msg' => '领取成功', 'rewardList' => $rewardList, 'key' => key($rewardList), 'integral_num' => $integral_num);
                } else {
                    return array('status' => false, 'msg' => '奖品列表为空');
                }
            } else {
                return array('status' => false, 'msg' => '奖品列表为空');
            }
        } else {
            return array('status' => false, 'msg' => '玩家为空');
        }
    }

    /**
     * @param $arr
     * @return int|string
     * @content  根据奖品概率进行抽奖
     */
    function get_rand($arr)
    {
        $result = -1;
        if (!empty($arr)) {
            //概率数组的总概率精度
            $sum = array_sum($arr); //计算数组中元素的和
            //概率数组循环
            foreach ($arr as $key => $cur) {
                $randNum = mt_rand(1, $sum * 10000);
                if ($randNum <= $cur * 10000) { //如果这个随机数小于等于数组中的一个元素，则返回数组的下标
                    $result = $key;
                    break;
                } else {
                    $sum -= $cur;
                }
            }
        }
        unset ($arr);
        return $result;
    }


    /**
     * @param $code
     * @param string $mark
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 判断用户是否已经注册(手机号/玩家ID查询)
     */
    function checkMemberRegister($code, $mark)
    {
        if (!empty($code)) {
            if ($mark == 'account') {
                # 账号密码查询
                $info = Db::table('member m')
                    ->field('m.*,mp.*,mc.*,ml.title,(select  COALESCE(sum(earnings_price),0) from member_business mb where mb.member_code = m.code and mb.status != -1 and place_status=1) combat_power')
                    ->leftJoin('member_property mp', 'mp.member_code=m.code and mp.is_fake=1')
                    ->leftJoin('member_collection mc', 'mc.member_code=m.code')
                    ->leftJoin('member_level ml', 'ml.level=m.level')
                    ->where(array('code' => strtoupper($code)))
                    ->find();
                if (!empty($info)) {
                    # 头像地址
                    $info['head_portrait'] = imgurl($info['head_portrait']);
                    # 微信收款码
                    $info['wx_img'] = imgurl($info['wx_img']);
                    # 支付宝收款码
                    $info['ali_img'] = imgurl($info['ali_img']);
                    # 银联收款码
                    $info['union_img'] = imgurl($info['union_img']);
                    $info['gold'] = priceFormat($info['gold']);
                    $info['bind_gold'] = priceFormat($info['bind_gold']);
                    $info['materials'] = priceFormat($info['materials']);
                    $info['integral'] = priceFormat($info['integral']);
                    $info['combat_power'] = priceFormat($info['combat_power']);
                    if ($info['status'] == 1) {
                        return array('status' => false, 'msg' => '未查到用户信息,未注册');
                    } else {
                        return array('status' => true, 'msg' => '查询成功', 'info' => $info);
                    }
                } else {
                    return array('status' => false, 'msg' => '未查到用户信息,未注册');
                }
            } else {
                # 手机号查询
                $info = Db::table('member m')
                    ->field('m.*,mp.*,mc.*,ml.title,(select  COALESCE(sum(earnings_price),0) from member_business mb where mb.member_code = m.code and mb.status != -1 and place_status=1) combat_power')
                    ->leftJoin('member_property mp', 'mp.member_code=m.code and mp.is_fake=1')
                    ->leftJoin('member_collection mc', 'mc.member_code=m.code')
                    ->leftJoin('member_level ml', 'ml.level=m.level')
                    ->where(array('phone' => $code))->find();
                if (!empty($info)) {
                    # 头像地址
                    $info['head_portrait'] = imgurl($info['head_portrait']);
                    # 微信收款码
                    $info['wx_img'] = imgurl($info['wx_img']);
                    # 支付宝收款码
                    $info['ali_img'] = imgurl($info['ali_img']);
                    # 银联收款码
                    $info['union_img'] = imgurl($info['union_img']);
                    $info['gold'] = priceFormat($info['gold']);
                    $info['bind_gold'] = priceFormat($info['bind_gold']);
                    $info['materials'] = priceFormat($info['materials']);
                    $info['combat_power'] = priceFormat($info['combat_power']);
                    $info['integral'] = priceFormat($info['integral']);
                    if ($info['status'] == 1) {
                        return array('status' => false, 'msg' => '未查到用户信息,未注册');
                    } else {
                        return array('status' => true, 'msg' => '查询成功', 'info' => $info);
                    }
                } else {
                    return array('status' => false, 'msg' => '未查到用户信息,未注册');
                }
            }
        } else {
            return array('status' => false, 'msg' => '查询条件存在空值');
        }
    }

    /**
     * @param $member_code
     * @param $member_name
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @content 登陆日志
     */
    function logLogin($member_code, $member_name)
    {
        $redis = new Redis();
        # 查询今天是否登陆过
        $logInfo = $redis->hGetJson('logLogin', $member_code);
        /*$logInfo = Db::table('log_login')->field('id,update_time')
            ->where("member_code='" . $member_code . "' and date(create_time) = '" . date('Y-m-d') . "'")->find();*/
        if (!empty($logInfo)) {
            # 今日登陆过
            Db::table('log_login')->where(array('id' => $logInfo['id']))
                ->update(array('update_time' => $logInfo['change_time'], 'change_time' => date('Y-m-d H:i:s')));
            # 更新redis
            $logInfo['update_time'] = $logInfo['change_time'];
            $logInfo['change_time'] = date('Y-m-d H:i:s');
            $redis->hSetJson('logLogin', $member_code, $logInfo);
        } else {
            $logInfo_arr = array(
                'member_code' => $member_code,
                'member_name' => $member_name,
                'create_time' => date('Y-m-d H:i:s'),
                'update_time' => date('Y-m-d H:i:s'),
                'change_time' => date('Y-m-d H:i:s')
            );
            # 没登陆过
            $logId = Db::table('log_login')->insertGetId($logInfo_arr);
            $logInfo_arr['id'] = $logId;
            # 计算过期时间
            $now = time();
            $over = strtotime(date("y-m-d 23:59:59", $now));
            $dif = $over - $now;
            $redis->hSetJson('logLogin', $member_code, $logInfo_arr, $dif);
        }
        return array('status' => true);
    }

    /**
     * @param string $code 用户ID
     * @param double $income 收益变化
     * @param int $type 类型
     * @param int $typeBranch 类型详细
     * 1  推荐玩家(金币收益)
     * 2  联盟推荐(金币收益)
     * 3  经营收益(经营收益)
     * 4  市场收益(经营收益)
     * 5  平台奖励(金币收益)
     * -1 后台修改
     * @content 添加收益变化记录
     * @return array
     */
    function addLog_income($code, $income, $type, $typeBranch = 0)
    {
        if (!empty($code) and !empty($income) and !empty($type)) {
            $info = array(
                'member_code' => $code,
                'income' => $income,
                'type' => $type,
                'type_branch' => $typeBranch,
                'create_time' => date("Y-m-d H:i:s")
            );
            $res = Db::table('log_earn')->insert($info);
            return array('status' => true, 'msg' => $res);
        } else {
            return array('status' => false, 'msg' => '存在空值');
        }
    }

    /**
     * @param string $code 用户ID
     * @param double $gold 金币变化值
     * @param int $type 类型
     * 1    转出
     * 2    转入
     * 3  系统赠送
     * 4  活动奖励
     * 5  推荐玩家
     * 6  联盟推荐
     * 7  市场收益
     * 8  摊位租金
     * 9  合成宝石
     * 10 兑换材料
     * -1 后台修改
     * @param string $memberp_code 转入/转出的玩家ID
     * @param int $type_branch 活动详细类型
     * @param string $out_trade_no 充值订单编号
     * @return array
     * @content 添加金币变化记录
     */
    function addLog_gold($code, $gold, $type, $memberp_code = '', $type_branch = 0, $out_trade_no = '',$order_id=0)
    {
        if (!empty($code) and !empty($gold) and !empty($type)) {
            $info = array(
                'member_code' => $code,
                'gold_num' => $gold,
                'type' => $type,
                'create_time' => date("Y-m-d H:i:s"),
                'memberp_code' => $memberp_code,
                'type_branch' => $type_branch,
                'out_trade_no' => $out_trade_no,
                'order_id'=>$order_id
            );
            $res = Db::table('log_gold')->insert($info);
            return array('status' => true, 'msg' => $res);
        } else {
            return array('status' => false, 'msg' => '存在空值');
        }
    }

    /**
     * @param int $code 用户ID
     * @param double $integral 积分变化值
     * @param int $status 状态  1 获得  2 使用
     * @param int $type 类型
     * 1 升级使用
     * 2 积分兑换
     * 3 系统赠送
     * 4 活动赠送
     * 5 合成宝石
     * 6 摇奖使用
     * 7    转出
     * 8    转入
     * 9
     * -1  后台修改
     * @param string $memberp_code 转入/转出的玩家ID
     * @param int $type_branch 活动类型
     * @return array
     * @content 添加积分变化记录
     */
    function addLog_integral($code, $integral, $status, $type, $memberp_code = '', $type_branch = 0,$order_id=0)
    {
        if (!empty($code) and !empty($integral) and !empty($status) and !empty($type)) {
            $info = array(
                'member_code' => $code,
                'num' => $integral,
                'status' => $status,
                'type' => $type,
                'create_time' => date("Y-m-d H:i:s"),
                'memberp_code' => $memberp_code,
                'type_branch' => $type_branch,
                'order_id'=>$order_id
            );
            $res = Db::table('log_integral')->insert($info);
            return array('status' => true, 'msg' => $res);
        } else {
            return array('status' => false, 'msg' => '存在空值');
        }
    }

    /**
     * @param string $code 用户ID
     * @param double $materials 材料变化值
     * @param int $type 类型
     * 1 金币兑换 获得
     * 2 未交租冻结 恢复使用
     * 3 活动获得
     * -1 后台修改
     * @return array
     * @content 添加材料变化记录
     */
    function addLog_materials($code, $materials, $type, $status = 0, $type_branch = 0)
    {
        if (!empty($code) and !empty($materials) and !empty($type)) {
            $info = array(
                'member_code' => $code,
                'change_num' => $materials,
                'type' => $type,
                'status' => $status,
                'type_branch' => $type_branch,
                'create_time' => date("Y-m-d H:i:s"),
            );
            $res = Db::table('log_materials')->insert($info);
            return array('status' => true, 'msg' => $res);
        } else {
            return array('status' => false, 'msg' => '存在空值');
        }
    }

    /**
     * @param string $table
     * @param string $field
     * @param $_where
     * @param array $order
     * @param bool $pageMark
     * @param int $listRows
     * @param null $query
     * @param null $page
     * @return array|\PDOStatement|string|\think\Collection|\think\Paginator
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 记录
     */
    function logInfo($table, $field = '*', $_where, $order = ['id' => 'desc'], $pageMark = false, $listRows = 10, $query = null, $page = null)
    {
        if ($pageMark) {
            $info = Db::table($table)->field($field)->where($_where)->order($order)->paginate($listRows, false, ['query' => $query]);
        } else {
            if (!is_null($listRows) and !is_null($page))
                $info = Db::table($table)->field($field)->where($_where)->order($order)->page($page, $listRows)->select();
            else
                $info = Db::table($table)->field($field)->where($_where)->order($order)->select();

        }
        return $info;
    }

    /**
     * @param int $tradAudit_id 交易记录的id
     * @param string $type trad_audit:交易审核/ complaint:玩家审核
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @content 违规判定
     */
    function violationJudgment($tradAudit_id, $type = 'trad_audit')
    {
        if (!empty($tradAudit_id)) {
            $redis = new Redis();
            # 查询是否操作过
            $operation = Db::table($type)->where(array('id' => $tradAudit_id))->find();
            $mark = true;
            $type_mark = true;//是否是生意投诉
            if ($operation['type_mark'] == 1 or $operation['type_mark'] == 2) {
                # 是 1 聊天内投诉  2 交易厅内投诉
                $type_mark = false;
            }
            if ($type == 'trad_audit') {
                $trad_audit = $operation;
                if ($operation['is_violations'] == 2) {
                    $mark = false;
                }
            } else {
                $trad_audit = Db::table("trad_audit")->where(array("id" => $operation['trad_audit_id']))->find();
                if ($operation['status'] == 2) {
                    $mark = false;
                }
            }
            if ($mark) {
                # 买家生意删除
                if ($type_mark) {
                    // $res = Db::table('member_business')->where(array('id' => $operation['buyer_business_id']))->update(array('status' => -1));
                    $buy_is_ingrid = $operation['buy_grid'];
                    if ($type == 'complain') {
                        $trade_info = Db::table("trade_audit")->field('buy_grid,sell_grid')->where(array("id" => $operation['trad_audit_id']))->find();
                        $buy_is_ingrid = $trade_info['buy_grid'];
                        $trad_audit['trad_status'] = 1;
                        $trad_audit['sell_grid'] = $trade_info['sell_grid'];
                    }
                    # 判断是否在栏位中
                    // $buy_is_ingrid = Db::table("member_business_grid")->field("id,grid")
                    //     ->where(array("member_code" => $operation['buy_code'], "member_business_id" => $operation['buyer_business_id']))->find();
                    if (!empty($buy_is_ingrid)) {
                        # 解绑玩家栏位
                        Db::table("member_business_grid")->where(array("id" => $buy_is_ingrid['id']))->update(array("status" => 1, "member_business_id" => 0, "start_time" => date("Y-m-d H:i:s")));
                        # 更改买家栏位状态
                        $buy_business_list = $redis->hGetJson("member_business", $operation['buy_code']);
                        $buy_business_list[$buy_is_ingrid - 1] = array("mbg_id" => $buy_business_list[$buy_is_ingrid - 1]['mbg_id'], "open_status" => 1, "member_business_id" => 0, "start_time" => date("Y-m-d H:i:s"), "grid" => $buy_is_ingrid);
                        $redis->hSetJson("member_business", $operation['buy_code'], $buy_business_list);
                    }
                    # 归还卖家生意(状态改为出售中)
                    Db::table('member_business')->where(array('id' => $operation['industry_id']))
                        ->update(array('status' => 3, "sale_time" => date("Y-m-d H:i:s"), "opera_start_time" => date("Y-m-d H:i:s")));
                    $business_info = Db::table("member_business")->where(array("id" => $operation['industry_id']))->find();
                    # 判断该生意是否是完成后投诉，完成前更改卖家栏位状态，完成后放仓库里
                    $business_info['sell_grid'] = null;
                    if ($trad_audit['trad_status'] == 1) {
                        # 完成前判断是栏位出售还是仓库出售
                        if (!empty($trad_audit['sell_grid'])) {
                            $business_info['sell_grid'] = $trad_audit['sell_grid'];
                            $sell_business_list = $redis->hGetJson("member_business", $operation['sell_code']);
                            $sell_business_list[$trad_audit['sell_grid'] - 1] = array("mbg_id" => $sell_business_list[$trad_audit['sell_grid'] - 1]['mbg_id'], "open_status" => 1, "status" => 3, "sale_price" => $business_info['sale_price'], "sale_time" => date("Y-m-d H:i:s"),
                                "team_id" => $business_info['team_id'], "opera_start_time" => date("Y-m-d H:i:s"), "grid" => $trad_audit['sell_grid']);
                            $redis->hSetJson("member_business", $operation['sell_code'], $sell_business_list);
                        } else {
                            $redis->hDel("wareHouse", $operation['sell_code']);
                        }
                    }
                    # 放入交易池
                    # 计算当前出售价格处于哪种收益阶段
                    $detail = getsIndustryDetail($business_info['industry_id']);
                    foreach ($detail['cycleIncome'] as $k => $v) {
                        if ($v['min_num'] <= $business_info['sale_price'] and $business_info['sale_price'] < $v['max_num']) {
                            $business_info['cycle_period'] = $v['cycle_period'];
                            $business_info['day_income'] = $v['day_income'];
                            break;
                        }
                    }
                    # 将用户生意信息存入售卖池中
                    $sale_list = $redis->hGetJson("member_sale_bussiness", $business_info['earnings_level']);
                    if (empty($sale_list)) {
                        $sale_list = array();
                    }
                    $business_info['sell_member_name'] = $operation['sell_name'];
                    $business_info['sell_member_phone'] = $operation['sell_phone'];
                    $business_info['sell_grid'] = $operation['sell_grid'];
                    array_push($sale_list, $business_info);
                    $redis->hSetJson("member_sale_bussiness", $business_info['earnings_level'], $sale_list);
                    # 交易记录改为违规冻结
                    Db::table('log_trad')->where(array('member_business_id' => $operation['industry_id']))->update(array('is_violations' => 2));
                    # 减掉团队提成
                    $group_log_list = Db::table("log_gold")->where(array("type" => 7, "member_business_id" => $business_info['id']))->select();
                    if (!empty($group_log_list)) {
                        foreach ($group_log_list as $k => $v) {
                            Db::table("member_property")->where(array("member_coe" => $v['member_code']))->setDec("gold", $v['gold_num']);
                            $_p_info = $redis->hGetJson("memberInfo", $v['member_code']);
                            $_p_info['gold'] -= $v["gold_num"];
                            $redis->hSetJson("memberInfo", $v['member_code'], $_p_info);
                        }
                        Db::table("log_gold")->where(array("type" => 7, "member_business_id" => $business_info['id']))->delete();
                    }
                }
                # 购买方账号冻结
                Db::table('member')->where(array('code' => $operation['buy_code']))->update(array('member_violations' => 2));
                # 增加购买方违规次数
                Db::table('member')->where(array('code' => $operation['buy_code']))->setInc('infraction', 1);
                # 冻结买方缓存信息
                $buy_member_info = $redis->hGetJson("memberInfo", $operation['buy_code']);
                $buy_member_info['member_violations'] = 2;
                $buy_member_info['infraction'] += 1;
                $redis->hSetJson("memberInfo", $operation['buy_code'], $buy_member_info);
                # 交易审核状态改为冻结
                if ($type == 'complaint') {
                    $_opera_id = $operation['trad_audit_id'];
                    # 玩家投诉 状态改为已处理
                    Db::table('complaint')->where(array('id' => $tradAudit_id))->update(array('status' => 2, 'is_violations' => 2, 'handle_status' => 1, 'handle_time' => date("Y-m-d H:i:s")));
                    if ($operation['type_mark'] == 2) {
                        # 交易厅内投诉 , 更改状态:审核通过 , 出售中
                        Db::table('trading_room')->where(array('id' => $_opera_id))->update(array(
                            'report_status' => 1,
                            'status' => 1,
                            'buyer_code' => '',
                            'buyer_name' => '',
                            'buyer_head' => '',
                            'order_time' => null,
                            'pay_time' => null,
                            'confirm_time' => null,
                            'trading_proof' => ''
                        ));
                        # 买家 member_property  加记录  解冻时需要
                        $tradingRoomId = Db::table('member_property')->field('trading_room_id')->where(array('member_code' => $operation['buy_code']))->find()['trading_room_id'];
                        if (!empty($tradingRoomId)) {
                            $tradingRoomId .= ',' . $_opera_id;
                        } else {
                            $tradingRoomId = $_opera_id;
                        }
                        Db::table('member_property')->where(array('member_code' => $operation['buy_code']))->update(array('trading_room_id' => $tradingRoomId));
                    }
                } else {
                    $_opera_id = $tradAudit_id;
                }
                if ($type_mark) {
                    Db::table('trad_audit')->where(array('id' => $_opera_id))->update(array('is_violations' => 2, 'confirm_time' => date("Y-m-d H:i:s")));
                }
                # 发送模板消息
                #
                #
                #
                return array('status' => true, 'msg' => '判定成功');

            } else {
                # 已经操作过
                return array('status' => false, 'msg' => '已被冻结');
            }
        } else {
            return array('status' => false, 'msg' => '缺少参数');
        }
    }
}